package router

import (
	"go-gin-api/internal/pkg/core"
	"go-gin-api/internal/pkg/db"
	"go-gin-api/internal/router/middleware"
	"go-gin-api/pkg/errors"

	"go.uber.org/zap"
)

type resource struct {
	mux    core.Mux
	logger *zap.Logger
	db     db.Repo
	// grpConn grpc.ClientConn
	middles middleware.Middleware
}

type Server struct {
	Mux core.Mux
	Db  db.Repo
	// GrpClient grpc.ClientConn
}

func NewHTTPServer(logger *zap.Logger) (*Server, error) {
	if logger == nil {
		return nil, errors.New("logger required")
	}

	r := new(resource)
	r.logger = logger

	// openBrowserUri := configs.ProjectDomain + configs.ProjectPort

	// 初始化 DB
	dbRepo, err := db.New()
	if err != nil {
		logger.Fatal("new db err", zap.Error(err))
	}
	r.db = dbRepo

	// // 初始化 gRPC client
	// gRPCRepo, err := grpc.New()
	// if err != nil {
	// 	logger.Fatal("new grpc err", zap.Error(err))
	// }
	// r.grpConn = gRPCRepo

	mux, err := core.New(logger,
		core.WithEnableCors(),
		core.WithEnableRate(),
	)

	if err != nil {
		panic(err)
	}

	r.mux = mux
	r.middles = middleware.New(logger, r.db)

	// 设置 API 路由
	setApiRouter(r)

	s := new(Server)
	s.Mux = mux
	s.Db = r.db
	// s.GrpClient = r.grpConn

	return s, nil
}
